package com.lfnyxy.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Service {
    private static final String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String getMD5Encode(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return byteArrayToHexString(md.digest(str.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    //客户端固定盐
    private static final String client_salt = "1a2b3c4d5e6f7g8h9j0k";

    //客户端生成加密密码
    public static String inputPassToFormPass(String inputPass){
        String str = ""+client_salt.charAt(0)+client_salt.charAt(2)+inputPass+client_salt.charAt(5)+client_salt.charAt(9);
        System.out.println(str);
        return getMD5Encode(str);
    }

    public static String formPassToDbPass(String formPass, String salt){
        String str = salt.charAt(0)+salt.charAt(2)+formPass+salt.charAt(5)+salt.charAt(9);
        return getMD5Encode(str);
    }

    public static String inputPassToDbPass(String inputPass, String saltDb){
        String formPass = inputPassToFormPass(inputPass);
        String dbPass = formPassToDbPass(formPass, saltDb);
        return dbPass;
    }


}